<?php

namespace app\api\logic;

use app\admin\logic\system\SystemConfigLogic;
//use app\admin\model\finance\UserCommissionLog;
//use app\admin\model\finance\UserCommissionWithdraw;
use app\admin\model\finance\UserMoneyLog;
//use app\admin\model\finance\Withdraw;
//use app\admin\model\marketing\MoneyRecharge;
use app\admin\model\user\UserMember;
use app\basic\BaseLogic;
use exception\ApiException;

class WalletLogic extends BaseLogic
{
    protected $user_commission_log_model;
    protected $user_commission_withdraw_model;

    protected $money_recharge;

     /**
     * 错误信息
     * @var string
     */
    protected $error = '';

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new UserMember();
//        $this->user_commission_log_model = new UserCommissionLog();
//        $this->user_commission_withdraw_model = new UserCommissionWithdraw();
//        $this->money_recharge = new MoneyRecharge();
    }

    /**
     * 获取钱包概览
     * @param int $userId 用户ID
     * @return array
     */
    public function getWalletOverview($userId)
    {
        $user = $this->model->where("id",$userId)->find();
        
        // 计算累计佣金
//        $totalCommission = $this->user_commission_log_model
//            ->where('user_id', $userId)
//            ->where('money', '>', 0)
//            ->sum('money');
        $totalCommission = 0;
            
        return [
            'balance' => $user['money'] ?? '0.00',
            'commission' =>  '0.00',
            'total_commission' => $totalCommission ?? '0.00'
        ];
    }

    /**
     * 获取收支记录
     */
    public function getMoneyLog($userId, $page, $limit)
    {
        $query = UserMoneyLog::where('user_id', $userId);
        $total = $query->count();
        $list = $query->page($page, $limit)
            ->order('create_time', 'desc')
            ->select();
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 获取提现记录
     */
    public function getWithdrawLog($userId, $page, $limit)
    {
        $query = $this->user_commission_withdraw_model->where('user_id', $userId);
        $total = $query->count();
        $list = $query->page($page, $limit)
            ->order('create_time', 'desc')
            ->select();
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 申请提现
     * @param int $userId 用户ID
     * @param array $params 提现参数
     * @return bool
     */
    public function createWithdraw($userId, $params)
    {
        // 参数验证
        $validate = new \think\Validate();
        $validate->rule([
            'money' => 'require|float|gt:0',
            'type' => 'require|in:1,2',
            'account' => 'require|length:2,100',
            'real_name' => 'require|length:2,50'
        ]);
        
        if (!$validate->check($params)) {
            $this->setError($validate->getError());
            return false;
        }

        $systemConfigLogic = new SystemConfigLogic();
        $systemInfo = $systemConfigLogic->getConfigByGroup('withdraw');

        // 获取用户信息
        $user = $this->model->where("id",$userId)->find();
        if (empty($user)) {
            $this->setError('用户不存在');
            return false;
        }

        // 检查提现金额
        if ($user['commission_money'] < $params['money']) {
            $this->setError('可提现佣金不足');
            return false;
        }

        // 最低提现金额限制
        if ($params['money'] < $systemInfo['min_price']) {
            $this->setError('最低提现金额为10元');
            return false;
        }

        // 计算手续费(2%) TODO 需要通过后台设置的获取
        $serviceFee = round($params['money'] * bcdiv($systemInfo['handling_fee'],100,2), 2);
        $realMoney = $params['money'] - $serviceFee;

        // 开启事务
        $this->model->startTrans();
        try {
            // 创建提现记录
            $result = $this->user_commission_withdraw_model->insert([
                'user_id' => $userId,
                'money' => $params['money'],
                'service_fee' => $serviceFee,
                'real_money' => $realMoney,
                'type' => $params['type'],
                'account' => $params['account'],
                'real_name' => $params['real_name'],
                'status' => 0,
                'create_time' => time()
            ]);
            if (!$result) {
                throw new \Exception('提现申请失败');
            }
            // 扣除用户可用佣金
            $result = $this->model->where('id', $userId)
                ->dec('commission_money', $params['money'])
                ->update();
            if (!$result) {
                throw new \Exception('佣金扣除失败');
            }

            // 记录佣金变动日志
            $result = $this->user_commission_log_model->insert([
                'user_id' => $userId,
                'money' => -$params['money'],
                'before' => $user['commission_money'],
                'after' => $user['commission_money'] - $params['money'],
                'title' => '佣金提现',
                'memo' => '提现'.$params['money'].'元，手续费'.$serviceFee.'元',
                'create_time' => time()
            ]);
            if (!$result) {
                throw new \Exception('记录变动日志失败');
            }
            // 提交事务
            $this->model->commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            $this->model->rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 获取佣金记录
     * @param int $userId 用户ID
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public function getCommissionLog($userId, $page, $limit)
    {
        $query = $this->user_commission_log_model->where('user_id', $userId);
        
        // 获取总记录数
        $total = $query->count();
        
        // 获取列表数据
        $list = $query->field('id, money, title, memo, create_time')
            ->page($page, $limit)
            ->order('create_time', 'desc')
            ->select()
            ->each(function($item) {
                // 格式化金额显示
                $item['money'] = sprintf("%.2f", $item['money']);
                return $item;
            })
            ->toArray();
            
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

     /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 设置错误信息
     * @param string $error
     */
    protected function setError($error)
    {
        $this->error = $error;
    }

    /**
     * 获取充值规格列表
     * @return array
     */
    public function getRechargeConfig()
    {
        return $this->money_recharge->where('status', 1)
            ->field('id, amount')
            ->select()
            ->toArray();
    }

    /**
     * 创建充值订单
     * @param int $userId 用户ID
     * @param array $params 参数
     * @return array|bool
     */
    public function createRecharge($userId, $params)
    {
        // 参数验证
        $validate = new \think\Validate();
        $validate->rule([
            'config_id' => 'require|number',
            'pay_type' => 'require|in:1,2'
        ]);
        
        if (!$validate->check($params)) {
            $this->setError($validate->getError());
            return false;
        }

        // 获取充值规格
        $config = $this->money_recharge
            ->where('id', $params['config_id'])
            ->where('status', 1)
            ->find();
            
        if (!$config) {
            $this->setError('充值规格不存在');
            return false;
        }

        // 生成订单号
        $orderNo = date('YmdHis') . mt_rand(1000, 9999);

        // 创建充值订单
        $order = [
            'order_no' => generateOrderNo("rc_{$userId}"),
            'user_id' => $userId,
            'money' => $config['amount'],
            'give_money' => 0,
            'pay_type' => $params['pay_type'],
            'pay_status' => 0,
            'create_time' => time()
        ];
        if (!$this->model->table('eb_money_recharge_order')->insert($order)) {
            $this->setError('创建充值订单失败');
            return false;
        }
        // 生成支付参数
        $payData = $this->createPayParams($orderNo, $config['money'], $params['pay_type']);
        if (!$payData) {
            $this->setError('生成支付参数失败');
            return false;
        }
        return [
            'order_no' => $orderNo,
            'money' => $config['money'],
            'pay_data' => $payData
        ];
    }

    /**
     * 生成支付参数（需要根据实际支付接口实现）
     * @param string $orderNo 订单号
     * @param float $money 金额
     * @param int $payType 支付方式
     * @return string|bool
     */
    protected function createPayParams($orderNo, $money, $payType)
    {
        // TODO: 对接实际的支付接口
        // 这里需要根据您使用的支付接口来实现
        // 返回支付所需的参数（如支付宝支付表单、微信支付参数等）
        return 'payment_params';
    }

}